//
//  udpSocket.m
//  FFmpeg_X264_Codec
//
//  Created by luwinglee on 16/1/8.
//  Copyright © 2016年 suntongmian@163.com. All rights reserved.
//

#import "udpSocket.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

@implementation udpSocket
{
    int                m_socket;
    struct sockaddr_in m_to_addr;  //sendto中使用的对方地址
    struct sockaddr_in m_from_addr;//在recvfrom中使用的对方主机地址
    unsigned int       m_fromLen;
    char recvBuffer[128];
}


-(id)init
{
    self = [super init];
    if (self!=nil) {
        return self;
    }
    else
        return nil;
}

-(int) createUdpByIpAddr:(char *)ipAddr andPort:(int) ipPort
{
    m_socket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if(m_socket < 0)
    {
        printf("create socket error\n");
        return -1;
    }
    else
        printf("create socekt ok\n");
    
    memset(&m_to_addr,0,sizeof(m_to_addr));
    m_to_addr.sin_family=AF_INET;
    m_to_addr.sin_addr.s_addr=inet_addr(ipAddr);
    m_to_addr.sin_port = htons(ipPort);
    
    return 0;
}

-(void) releaseUdp
{
    close(m_socket);
}

-(int) sendData:(char *) dataBuf andSize:(int) dataSize
{
    int ret = -1;
    
    ret = (int)sendto(m_socket,dataBuf,dataSize,0,(struct sockaddr*)&m_to_addr,sizeof(m_to_addr));
    
    if(ret != dataSize)
    {
        printf("sendto() error code :%d\n",ret);
    }
    
    return ret;
}

-(int) recvData:(int)maxRecvSize
{
    if (maxRecvSize > MAX_RECV_BUF_SIZE) {
        maxRecvSize = MAX_RECV_BUF_SIZE;
    }
    
    int fromLen = sizeof(m_from_addr);
    int ret = (int)recvfrom(m_socket,recvBuffer,maxRecvSize,0,(struct sockaddr*)&m_from_addr,&fromLen);
    
    if(ret < 0)
    {
        printf("()recvfrom() error :%d\n",ret);
    }
    else
        m_recv_data_cb(recvBuffer,ret);

    
    return ret;
}

@end
